/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.search

import org.joda.time.DateTime
import org.joda.time.LocalDateTime
import org.joda.time.DateTimeZone
import org.joda.time.format.DateTimeFormatter
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.format.DateTimeFormat
import java.util.Date

class DateHelper {
    //private static DateTimeFormatter _dateFormatter
    public static PUBLISHED_PATTERN = 'dd MMM yyyy HH:mm:ss'
    public static HTTP_PATTERN = 'EEE, dd MMM yyyy HH:mm:ss zzz'

    // Date far into the future used to "unpublish" an item
    public static UNPUBLISH_DATE = '01 Jan 3000 00:00:00'

    public static DateTime stringToDateTime(String s) {
        DateTimeFormatter fmt = getISODateFormatter()
        return fmt.parseDateTime(s)
    }

    private static DateTimeFormatter getISODateFormatter() {
        DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC)
        return fmt
        /*
        if (!_dateFormatter) {
            _dateFormatter = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC)
        }
        return _dateFormatter
        */
    }

    public static DateTimeFormatter getHttpFormatter() {
        return _getFormatter(HTTP_PATTERN, DateTimeZone.UTC)
    }

    public static DateTimeFormatter getPublishedFormatter() {
        DateTimeZone defaultZone = DateTimeZone.getDefault()
        return _getFormatter(PUBLISHED_PATTERN, defaultZone)
    }

    private static DateTimeFormatter _getFormatter(String pattern, DateTimeZone tz) {
        DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern)
        if (tz) {
            fmt = fmt.withZone(tz)
        }
        return fmt
    }

    /**
     * Parse a datetime string using the published datetime pattern.  Assumes
     * that the datetime is the local server timezone, then converts to UTC.
     *
     * @param s
     * @return
     */
    public static DateTime publishedStringToDateTime(String s) {
        DateTimeFormatter fmt = _getFormatter(PUBLISHED_PATTERN, null)
        return fmt.parseDateTime(s).withZone(DateTimeZone.UTC)
    }

    public static DateTime now() {
        return new DateTime(DateTimeZone.UTC)
    }

    public static DateTime nowLocal() {
        return new DateTime()
    }

}
